<?php

namespace App\GraphQL\Queries\Group;

use App\Models\Group;
use App\Models\GroupMember;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class QueryGroups
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $query = Group::query();
        
        $page = $args['input']['page'];
        $keywords = $args['input']['keywords'];
        $cate = $args['input']['cate']?:'DEVICE';
        $authUser = auth()->user();
        if($cate){
            $query->where('cate',$cate);
        }
        if($authUser->role_code !== 'ADMIN'){
            $query->where(function($query) use(&$authUser){
                $groupIds = GroupMember::select('group_id')->where('user_id',$authUser->id)->pluck('group_id');
                $query->where('user_id',$authUser->id)->orWhereIn('id',$groupIds);
            });
        }
        if($keywords){
            $query->where('name','LIKE',"%$keywords%");
        }
        $pageInfo = $query->paginate($args['input']['limit'],['*'],'page',$page);
        return [
            'data'=>$pageInfo->items(),
            'paginatorInfo'=>[
                'count'=> $pageInfo->count(),
                'currentPage'=>$pageInfo->currentPage(),
                'firstItem'=>$pageInfo->firstItem(),
                'hasMorePages'=>$pageInfo->hasMorePages(),
                'lastItem'=>$pageInfo->lastItem(),
                'lastPage'=>$pageInfo->lastPage(),
                'perPage'=>$pageInfo->perPage(),
                'total'=>$pageInfo->total()
            ]
        ];
    }
}
